package com.guashu.jaywayjsonpath.renhang;

import java.sql.*;
import java.util.*;

import com.alibaba.fastjson.JSON;

public class DatabaseUtil {
    static {
        try {
            // 显式加载MySQL JDBC驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            throw new RuntimeException("无法加载MySQL驱动程序", e);
        }
    }

    public Map<String, List<FieldInfo>> queryTableStructure(String tableName) {
        // 存储结果的Map，key是division_node
        Map<String, List<FieldInfo>> tableStructure = new LinkedHashMap<>();
        // JDBC连接字符串
        String connectionUrl = "jdbc:mysql://localhost:3306/renhang?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
        // SQL查询语句，加入division_node并按division_node和id排序
        String sql = "SELECT rule_key, step,`desc`, dtype, division_node FROM " + tableName + " ORDER BY division_node, id";

        try (Connection conn = DriverManager.getConnection(connectionUrl, "root", "root");
             Statement stmt = conn.createStatement();
             ResultSet resultSet = stmt.executeQuery(sql)) {

            while (resultSet.next()) {
                // 获取字段信息并创建FieldInfo对象
                String ruleKey = resultSet.getString("rule_key");
                String step = resultSet.getString("step");
                String description = resultSet.getString("desc");
                String dataType = resultSet.getString("dtype");
                String divisionNode = resultSet.getString("division_node"); // 获取division_node字段的值

                FieldInfo fieldInfo = new FieldInfo();
                fieldInfo.setRuleKey(ruleKey);
                fieldInfo.setStep(step);
                fieldInfo.setDescription(description);
                fieldInfo.setDataType(dataType);
                fieldInfo.setDivisionNode(divisionNode);

                // 将FieldInfo对象添加到对应division_node的列表中
                tableStructure.computeIfAbsent(divisionNode, k -> new ArrayList<>()).add(fieldInfo);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return tableStructure;
    }

    // 主方法，用于测试
    public static void main(String[] args) {
        DatabaseUtil dbUtil = new DatabaseUtil();
        Map<String, List<FieldInfo>> result = dbUtil.queryTableStructure("business_parse_rule_renhang_v4");

        // 使用fastjson格式化打印结果
        String jsonString = JSON.toJSONString(result, true);
        System.out.println("打印结果：" + jsonString);
    }
}

// FieldInfo类可能需要加入divisionNode属性和相应的getter/setter方法
